package com.daoshu.mti.kafkaclient.handle;

import com.alibaba.fastjson.JSON;
import com.daoshu.mti.kafkaclient.bean.TKmJurisdictionEntity;
import com.daoshu.mti.kafkaclient.bean.TKmMhlgEntity;
import com.daoshu.mti.kafkaclient.bean.TKmZdryYjEntity;
import com.daoshu.mti.kafkaclient.constant.Topic;
import com.daoshu.mti.kafkaclient.consumer.TKmMhlgBaseConsumer;
import com.daoshu.mti.kafkaclient.service.*;
import com.daoshu.mti.kafkaclient.utils.AddressOrLngLatConvertUtil;
import com.daoshu.mti.kafkaclient.utils.AddressResolutionUtil;
import com.daoshu.mti.kafkaclient.utils.ZdryYjUtilBean;
import com.daoshu.mti.kafkaclient.websocket.SocketType;
import com.daoshu.mti.kafkaclient.websocket.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname TKmTldpHandle
 * @Description TODO
 * @Date 2020/1/17 21:15
 * @Created by duchaof
 * @Version 1.0
 */
@Slf4j
@Component
public class TKmMhlgHandle extends TKmMhlgBaseConsumer {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private TKmMhlgService tKmMhlgService;

    @Autowired
    private TKmZdryYjService tKmZdryYjService;

    @Autowired
    private WebSocketUtils webSocketUtils;

    @Autowired
    private TKmMhdzService tKmMhdzService;

    @Autowired
    private TLfZdryBaseService tLfZdryBaseService;

    @Autowired
    private TKmJurisdictionService tKmJurisdictionService;
    @Autowired
    private AddressOrLngLatConvertUtil addressUtil;

    private static Lock lock = new ReentrantLock();

    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void onDealMessage(String message) {
        try {
            log.info("接收到topic：" + Topic.MHLG + "的消息" + ",线程：" + Thread.currentThread().getName() + "在"
                    + sdf.format(new Date()) + "开始处理接受到的消息：" + message);
            TKmMhlgEntity tKmMhlgEntity = JSON.parseObject(message, TKmMhlgEntity.class);

            Integer res = null;
            lock.lock();
            try {
                // 根据身份证号  和 预警时间判断重复数据
                Boolean repeatFlag = tKmMhlgService.judgeRepeatData(tKmMhlgEntity);
                if (repeatFlag) return;

                res = tKmMhlgService.insert(tKmMhlgEntity);
            } catch (Exception e) {
                log.error("插入民航离岗发生异常：=========》{}", e.getMessage());
            } finally {
                lock.unlock();
            }
            if (res > 0) {
                //log.info("数据插入成功，插入成功的数据为：" + message);
                TKmZdryYjEntity tKmZdryYjEntity = tKmMhlgEntity.transtoZdryEntity();
                Map<String, Object> fromMap = tKmMhdzService.queryCityByMhCode(tKmMhlgEntity.getSegDeptCode());
                if (null != fromMap) {
                    if (fromMap.containsKey("province") && fromMap.get("province") != null) {
                        tKmZdryYjEntity.setSendPro(fromMap.get("province").toString());
                    }
                    if (fromMap.containsKey("city") && fromMap.get("city") != null) {
                        tKmZdryYjEntity.setSendCity(fromMap.get("city").toString());
                    }
                    if (fromMap.containsKey("lng") && fromMap.get("lng") != null) {
                        tKmZdryYjEntity.setSendLng(fromMap.get("lng").toString());
                    }
                    if (fromMap.containsKey("lat") && fromMap.get("lat") != null) {
                        tKmZdryYjEntity.setSendLat(fromMap.get("lat").toString());
                    }
                    if (fromMap.get("city").toString().equals("昆明") || fromMap.get("city").toString().equals("昆明市")) {
                        tKmZdryYjEntity.setInOut(2);
                        if (fromMap.containsKey("lng") && fromMap.get("lng") != null) {
                            tKmZdryYjEntity.setX(fromMap.get("lng").toString());
                        }
                        if (fromMap.containsKey("lat") && fromMap.get("lat") != null) {
                            tKmZdryYjEntity.setY(fromMap.get("lat").toString());
                        }
                    }
                } else {
                    if (null != tKmMhlgEntity.getSegDeptCodeCn() && tKmMhlgEntity.getSegDeptCodeCn().length() > 0) {
                        Map<String, String> sendAddress = addressUtil.checkXY(tKmMhlgEntity.getSegDeptCodeCn());
                        tKmZdryYjEntity.setSendLng(sendAddress.get("lng"));
                        tKmZdryYjEntity.setSendLat(sendAddress.get("lng"));
                        if (sendAddress.containsKey("search") && null != sendAddress.get("search")) {
                            Map<String, String> proCityMap = AddressResolutionUtil.addressResolution(sendAddress.get("search"));
                            tKmZdryYjEntity.setSendPro(addressUtil.InterceptProvince(proCityMap.get("province")));
                            tKmZdryYjEntity.setSendCity(addressUtil.InterceptCity(proCityMap.get("city")));
                            if (proCityMap.get("city").equals("昆明") || proCityMap.get("city").equals("昆明市")) {
                                tKmZdryYjEntity.setInOut(2);
                                tKmZdryYjEntity.setX(sendAddress.get("lng"));
                                tKmZdryYjEntity.setY(sendAddress.get("lat"));
                            }
                        }
                    }
                }
                Map<String, Object> toMap = tKmMhdzService.queryCityByMhCode(tKmMhlgEntity.getSegDestCode());
                if (null != toMap) {
                    if (toMap.containsKey("province") && toMap.get("province") != null) {
                        tKmZdryYjEntity.setEndPro(toMap.get("province").toString());
                    }
                    if (toMap.containsKey("city") && toMap.get("city") != null) {
                        tKmZdryYjEntity.setEndCity(toMap.get("city").toString());
                    }
                    if (toMap.containsKey("lng") && toMap.get("lng") != null) {
                        tKmZdryYjEntity.setEndLng(toMap.get("lng").toString());
                    }
                    if (toMap.containsKey("lat") && toMap.get("lat") != null) {
                        tKmZdryYjEntity.setEndLat(toMap.get("lat").toString());
                    }
                    if (toMap.get("city").toString().equals("昆明") || toMap.get("city").toString().equals("昆明市")) {
                        tKmZdryYjEntity.setInOut(1);
                        if (toMap.containsKey("lng") && toMap.get("lng") != null) {
                            tKmZdryYjEntity.setX(toMap.get("lng").toString());
                        }
                        if (toMap.containsKey("lat") && toMap.get("lat") != null) {
                            tKmZdryYjEntity.setY(toMap.get("lat").toString());
                        }
                    }
                } else {
                    if (null != tKmMhlgEntity.getSegDestCodeCn() && tKmMhlgEntity.getSegDestCodeCn().length() > 0) {
                        Map<String, String> endAddress = addressUtil.checkXY(tKmMhlgEntity.getSegDestCodeCn());
                        if (null != endAddress) {
                            tKmZdryYjEntity.setEndLng(endAddress.get("lng"));
                            tKmZdryYjEntity.setEndLat(endAddress.get("lat"));
                            if (endAddress.containsKey("search") && null != endAddress.get("search")) {
                                Map<String, String> proCityMap = AddressResolutionUtil.addressResolution(endAddress.get("search"));
                                tKmZdryYjEntity.setEndPro(addressUtil.InterceptProvince(proCityMap.get("province")));
                                tKmZdryYjEntity.setEndCity(addressUtil.InterceptCity(proCityMap.get("city")));
                                if (proCityMap.get("city").equals("昆明") || proCityMap.get("city").equals("昆明市")) {
                                    tKmZdryYjEntity.setInOut(1);
                                    tKmZdryYjEntity.setX(endAddress.get("lng"));
                                    tKmZdryYjEntity.setY(endAddress.get("lat"));
                                }
                            }
                        }
                    }
                }

                // 查询预警发生地的派出所代码和名称
                TKmJurisdictionEntity tKmJurisdictionEntity = tKmJurisdictionService.queryYjdPcsByLngAndLat(tKmZdryYjEntity.getX(), tKmZdryYjEntity.getY());
                if (null != tKmJurisdictionEntity) {
                    tKmZdryYjEntity.setYjdPcs(tKmJurisdictionEntity.getMc());
                    tKmZdryYjEntity.setYjdPcsCode(String.format("%.0f", Double.parseDouble(tKmJurisdictionEntity.getDm())));
                    tKmZdryYjEntity.setYjdSsfj(tKmJurisdictionEntity.getSsfj());
                }
                tKmZdryYjService.insert(tKmZdryYjEntity);
                ZdryYjUtilBean zdryYjUtilBean = tKmMhlgEntity.transtoZdryYjUtilBean();
                zdryYjUtilBean.setYjwybs(tKmZdryYjEntity.getWybs());

                if (null != tKmJurisdictionEntity) {
                    StringBuilder sb = new StringBuilder("重点人员【");
                    sb.append(tKmZdryYjEntity.getRyxm()).append("】在").append(tKmJurisdictionEntity.getMc()).append("的管辖范围内乘坐分机");
                    if (tKmZdryYjEntity.getInOut() == 1) {
                        sb.append("到达。");
                    } else if (tKmZdryYjEntity.getInOut() == 2) {
                        sb.append("离开。");
                    } else sb.append("。");
                    zdryYjUtilBean.setYjMsg(sb.toString());
                }
                if (null != tKmMhlgEntity.getCertNo()) {
                    //查询此条预警是否是灰名单 或者是 已稳控  如果是就不推送
                    TKmZdryYjEntity entity = tKmZdryYjService.authGkjbAndWkzt(tKmMhlgEntity.getCertNo());
                    if (!ObjectUtils.isEmpty(entity)) {
                        return;
                    }
                    List<String> tokens = tKmZdryYjService.findWebsocketPsuhUserListBySfzh(tKmMhlgEntity.getCertNo());
                    if (null != tokens) {
                        webSocketUtils.sendWebsockMessageToUser(tokens,
                                Arrays.asList("mhlg", JSON.toJSONString(zdryYjUtilBean)), SocketType.ZDRRYJXX.getCode());
                    }
                }
                //webSocketUtils.sendWebsockMessageToAll(Arrays.asList("mhlg",JSON.toJSONString(zdryYjUtilBean)), SocketType.ZDRRYJXX.getName());
            } else {
                log.error("数据插入失败，插入失败的数据为：" + message);
            }
        } catch (Exception e) {
            log.error("插入数据库发生异常=====>{}", e.getMessage());
        }
    }
}
